package com.fenxiao.task.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.fenxiao.card.entity.Bankcard;
import com.fenxiao.card.service.CardService;
import com.fenxiao.common.Pager;
import com.fenxiao.mytask.entity.UserTask;
import com.fenxiao.mytask.service.UserTaskService;
import com.fenxiao.task.entity.Task;
import com.fenxiao.task.entity.TaskImg;
import com.fenxiao.task.entity.TaskScreenshot;
import com.fenxiao.task.service.TaskImgService;
import com.fenxiao.task.service.TaskService;
import com.fenxiao.user.entity.User;
import com.fenxiao.user.service.UserService;
import com.fenxiao.util.PromptMessage;
import com.fenxiao.util.Tools;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.weixin.po.OAuthInfo;
import com.weixin.utils.Utils;

import freemarker.core.ParseException;

public class TaskAction extends ActionSupport {
	private HttpServletRequest request;
	private HttpServletResponse response;	
	private HttpSession session;
	//任务编号
	private String taskCode;
	private TaskService taskService;
    private UserService userService;
    private  Map<String, Object> dataMap;
    
    private int page=1;
	private List<Task> taskList;
	List<TaskScreenshot> shotList;
	private Pager pageBean;
	private String search;
	
	private String taskTitle;
	private String taskTitle1;
	private String taskTitle2;
    
	private Task task;
	private TaskImgService taskImgService;
	private UserTaskService userTaskService;
	private User user;
	private File fileTest; // 接收这个上传的文件
	private String fileTestFileName;
	private File fileTest1; // 接收这个上传的文件
	private String fileTest1FileName;
	private String openId;
	private Long taskId;
	
	private static PromptMessage promptMessage = new PromptMessage();
	// 上传文件
	private File imgFile;
		// 上传文件名称
	private String imgFileFileName;
		// 上传文件类型
	private String imgFileContentType;
	private String imgList;
    private List<TaskImg> taskImgList;
    
private CardService cardService;
	
	private String mobile;
	private String userId;
	private List<File> uploadFileData;
	/** 文件名 */
	private List<String> uploadFileDataFileName;
	/** 文件内容类型 */
	private List<String> uploadFileDataContentType;
	
	private String msg;
	private String content;
	private String number;
	private String code1;
	
	private String dateNum;
	/**
	 * 分页查询需求
	 * @return
	 */
	public String queryTask(){
	request = ServletActionContext.getRequest();
    response = ServletActionContext.getResponse();
    HttpSession session = request.getSession();
    pageBean=taskService.findTaskPage(3, page, search);	
	taskList=pageBean.getList();	
	request.setAttribute("taskList", taskList);
	request.setAttribute("pageBean", pageBean);
	return "queryTask";	
		
	}
	
	/**
	 * 生成任务页面
	 * @return
	 */
	public String createTaskPage(){
	  request = ServletActionContext.getRequest();
	  response = ServletActionContext.getResponse();
	  HttpSession session = request.getSession();
	  task=taskService.queryTaskInfo(task.getTaskId());
	  
	  
	  request.setAttribute("task",task);
	  return "createTaskPage";	
	}
	/**
	 * 生成任务
	 * @return
	 */
	public String createTask(){
		Task task1=taskService.queryTaskInfo(task.getTaskId());
		task1.setTaskStatus(1);
		 request = ServletActionContext.getRequest();
         response = ServletActionContext.getResponse();
         Set set = new HashSet();
			HttpSession session = request.getSession();	
			int type = 0;
	        String[] str = { ".jpg", ".jpeg", ".bmp" ,".png",".gif"};  
	        //限定文件大小是4MB  
	        if(fileTest!=null){
	        if(fileTest.length()>2097152 ){  
	        	msg ="图片大小超出了2M";
	            return createTaskPage();  
	        } else{ 
	        
	        for (String s : str) {  
	            if (fileTestFileName.endsWith(s)) {  
	            	type =1;
	              String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
	               // String realPath ="d:/upload/faceimages";
	            	System.out.println(realPath);
	            	fileTestFileName=Tools.getRandomFileName()+s;
	                File saveFile = new File(new File(realPath),fileTestFileName);  //在该实际路径下实例化一个文件  
	                //判断父目录是否存在  
	                if(!saveFile.getParentFile().exists()){  
	                    saveFile.getParentFile().mkdirs();  
	                }  
	                try {  
	                    //执行文件上传  
	                    //FileUtils 类名 org.apache.commons.io.FileUtils;  
	                    //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
	                    FileUtils.copyFile(fileTest, saveFile);  
	                    task1.setTaskLogo("faceimages/"+fileTestFileName);
	                      
	                } catch (IOException e) {  
	                	msg ="图片上传失败";
	                    return createTaskPage();  
	                }  
	            }  
	        }  
	        if(type== 0){
	        	msg = "上传的图片类型错误";
	        	return createTaskPage();
	        }
	        }
	        }
	        if(imgList != null){
	    		String[] list = imgList.split("\\*");
	    		taskImgList= new ArrayList();
	    		for (int i = 0; i < list.length; i++) {
	    			TaskImg t= new TaskImg();
	    			t.setTask(task1);
	    			String url=list[i].substring(9, list[i].length());
	    			
	    			t.setImgUrl(url);
	    			Date date=new Date();
	    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    			t.setImgTime(sdf.format(date));
	    			taskImgList.add(t);
	    			
	            }
	    		set.addAll(taskImgList);
	    		task1.setTaskImgs(set);
	        }
	        task1.setShengc(task.getShengc());
	        task1.setTaskInfo(content);
		    task1.setTaskBeginTime(task.getTaskBeginTime());
		    task1.setTaskEndTime(task.getTaskEndTime());
		    task1.setAdUrl(task.getAdUrl());
		    task1.setDateNum(dateNum);
		    task1.setMobilePhone(task.getMobilePhone());
		    double a=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.45;
		    double b=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.3;
		    DecimalFormat    df   = new DecimalFormat("######0.00"); 
		    task1.setTaskBonus(Double.parseDouble(df.format(b)));
		    task1.setTaskBonus1(Double.parseDouble(df.format(a)));
		    task1.setTaskRemainderNumber(task.getTaskTotalNumber());
		    task1.setTaskSBonus(task.getTaskTotalBonus());
		    task1.setOriginalID(task.getOriginalID());
		    task1.setWeChat(task.getWeChat());
		    if(task.getProvince().equals("省")){
		    	task1.setProvince("全国");
		    }else{
		    	task1.setProvince(task.getProvince());
		    }
		    if(task.getCity().equals("市")){
		    	task1.setCity("全国");
		    }else{
		    	task1.setCity(task.getCity());
		    }
		    if(task.getArea().equals("区")){
		    	task1.setArea("全国");
		    }else{
		    	task1.setArea(task.getArea());
		    }
		    
		    
		    int i=taskService.updateTask(task1);
		    
		return queryTask();
	}
	/**
	 * 批量删除Task
	 */
	public String deleteAllTask(){
		int i= taskService.deleteAllTask(number);
		if(i>0){
			return queryTask();
		}else{
			msg="删除失败！";
		return queryTask();
		}
	}
	/**
	 * 删除task
	 */
	public String deleteTask(){
	int i= taskService.deleteTask(task.getTaskId());
	if(i>0){
		return queryTask();
	}else{
		msg="删除失败！";
	return queryTask();
	}
	}
	
	/**
	 * 添加任务页面
	 */
	public String addTaskPage(){
		 request = ServletActionContext.getRequest();
         response = ServletActionContext.getResponse();
			HttpSession session = request.getSession();	
		List<User> userList=userService.queryUserList();
		request.setAttribute("userList", userList);
		return "addTaskPage";
	}	
	/**
	 * 添加任务
	 */
	public String addTask(){
		request = ServletActionContext.getRequest();
        response = ServletActionContext.getResponse();
			HttpSession session = request.getSession();	
			int type = 0;
	        String[] str = { ".jpg", ".jpeg", ".bmp" ,".png",".gif"};  
	        //限定文件大小是4MB  
	        if(fileTest!=null){
	        if(fileTest.length()>2097152 ){  
	        	msg ="图片大小超出了2M";
	            return addTaskPage();  
	        } else{ 
	        
	        for (String s : str) {  
	            if (fileTestFileName.endsWith(s)) {  
	            	type =1;
	              String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
	               // String realPath ="d:/upload/faceimages";
	            	System.out.println(realPath);
	            	fileTestFileName=Tools.getRandomFileName()+s;
	                File saveFile = new File(new File(realPath),fileTestFileName);  //在该实际路径下实例化一个文件  
	                //判断父目录是否存在  
	                if(!saveFile.getParentFile().exists()){  
	                    saveFile.getParentFile().mkdirs();  
	                }  
	                try {  
	                    //执行文件上传  
	                    //FileUtils 类名 org.apache.commons.io.FileUtils;  
	                    //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
	                    FileUtils.copyFile(fileTest, saveFile);  
	                    task.setTaskLogo("faceimages/"+fileTestFileName);
	                      
	                } catch (IOException e) {  
	                	msg ="图片上传失败";
	                    return addTaskPage();  
	                }  
	            }  
	        }  
	        if(type== 0){
	        	msg = "上传的图片类型错误";
	        	return addTaskPage();
	        }
	        }
	        }
	        if(fileTest1!=null){
		        if(fileTest1.length()>2097152 ){  
		        	msg ="图片未上传或者图片大小超出了2M";
		            return addTaskPage();  
		        } else{ 
		        
		        for (String s : str) {  
		            if (fileTest1FileName.endsWith(s)) {  
		            	type =1;
		               String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
		                //String realPath ="d:/upload/faceimages";
		            	System.out.println(realPath);
		            	fileTest1FileName=Tools.getRandomFileName()+s;
		                File saveFile = new File(new File(realPath),fileTest1FileName);  //在该实际路径下实例化一个文件  
		                //判断父目录是否存在  
		                if(!saveFile.getParentFile().exists()){  
		                    saveFile.getParentFile().mkdirs();  
		                }  
		                try {  
		                    //执行文件上传  
		                    //FileUtils 类名 org.apache.commons.io.FileUtils;  
		                    //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
		                    FileUtils.copyFile(fileTest1, saveFile);  
		                    task.setTaskOr("faceimages/"+fileTest1FileName);
		                      
		                } catch (IOException e) {  
		                	msg ="图片上传失败";
		                    return addTaskPage();  
		                }  
		            }  
		        }  
		        if(type== 0){
		        	msg = "上传的图片类型错误";
		        	return addTaskPage();
		        }
		        }
		        }
	        user=userService.queryUserInfo(user);
	        task.setUser(user);
	        task.setTaskInfo(content);
	        task.setTaskStatus(1);
	        double a=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.45;
		    double b=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.3;
		    DecimalFormat    df   = new DecimalFormat("######0.00"); 
		    task.setTaskBonus(Double.parseDouble(df.format(b)));
		    task.setTaskBonus1(Double.parseDouble(df.format(a)));
	        Date date =new Date();
		   SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		   String  sd=sdf.format(date);
		   task.setPubTime(sd);
		     	
		   int i=taskService.addTask(task);
		
		
		return findTaskPage();
	}
	/**
	 * 分页查询所有的任务
	 */
	public String findTaskPage(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
	    HttpSession session = request.getSession();
	    pageBean=taskService.queryTaskPage(3, page, search);	
		taskList=pageBean.getList();	
		request.setAttribute("taskList", taskList);
		request.setAttribute("pageBean", pageBean);	
		return "findTaskPage";
	}
	
    /**
     * 详情	
     * @return
     */
	public String queryTaskInfo(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
		task=taskService.queryTaskInfo(task.getTaskId());
		request.setAttribute("task", task);	
        
     
		return  "queryTaskInfo";  
	}  
	
	/**
     * 修改任务	
     * @return
     */
	public String updtaeTask1Page(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
		task=taskService.queryTaskInfo(task.getTaskId());
		request.setAttribute("task", task);	
        
     
		return  "updtaeTask1";  
	} 
	/**
	 * 修改任务
	 * @return
	 */
	 public String updtaeTask1(){
		 Task task1=taskService.queryTaskInfo(task.getTaskId());
			 request = ServletActionContext.getRequest();
	         response = ServletActionContext.getResponse();
				HttpSession session = request.getSession();	
				int type = 0;
		        String[] str = { ".jpg", ".jpeg", ".bmp" ,".png",".gif"};  
		        //限定文件大小是4MB  
		        if(fileTest!=null){
		        if(fileTest.length()>2097152 ){  
		        	msg ="图片大小超出了2M";
		            return updtaeTask1Page();  
		        } else{ 
		        
		        for (String s : str) {  
		            if (fileTestFileName.endsWith(s)) {  
		            	type =1;
		              String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
		               // String realPath ="d:/upload/faceimages";
		            	System.out.println(realPath);
		            	fileTestFileName=Tools.getRandomFileName()+s;
		                File saveFile = new File(new File(realPath),fileTestFileName);  //在该实际路径下实例化一个文件  
		                //判断父目录是否存在  
		                if(!saveFile.getParentFile().exists()){  
		                    saveFile.getParentFile().mkdirs();  
		                }  
		                try {  
		                    //执行文件上传  
		                    //FileUtils 类名 org.apache.commons.io.FileUtils;  
		                    //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
		                    FileUtils.copyFile(fileTest, saveFile);  
		                    task1.setTaskLogo("faceimages/"+fileTestFileName);
		                      
		                } catch (IOException e) {  
		                	msg ="图片上传失败";
		                    return updtaeTask1Page();  
		                }  
		            }  
		        }  
		        if(type== 0){
		        	msg = "上传的图片类型错误";
		        	return updtaeTask1Page();
		        }
		        }
		        }
		        task1.setTaskInfo(content);
		        task1.setTaskTitle(task.getTaskTitle());
			    task1.setTaskBeginTime(task.getTaskBeginTime());
			    task1.setTaskEndTime(task.getTaskEndTime());
			    task1.setDateNum(task.getDateNum());
			    task1.setMobilePhone(task.getMobilePhone());
			    task1.setTaskStatus(task.getTaskStatus());
			    task1.setTaskBriefing(task.getTaskBriefing());
			   
			  
			    task1.setTaskTotalBonus(task.getTaskTotalBonus());
			    task1.setTaskTotalNumber(task.getTaskTotalNumber());
			    double a=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.45;
			    double b=(task.getTaskTotalBonus()/task.getTaskTotalNumber())*0.3;
			    DecimalFormat    df   = new DecimalFormat("######0.00"); 
			    task1.setTaskBonus(Double.parseDouble(df.format(a)));
			    task1.setTaskBonus1(Double.parseDouble(df.format(b)));
			    int i=taskService.updateTask(task1);
		return  findTaskPage();	    	 
	 }
	 /**
		 * 批量删除Task
		 */
		public String deleteAllTask1(){
			int i= taskService.deleteAllTask(number);
			if(i>0){
				return findTaskPage();
			}else{
				msg="删除失败！";
			return findTaskPage();
			}
		}
		/**
		 * 删除task
		 */
		public String deleteTask1(){
		int i= taskService.deleteTask(task.getTaskId());
		if(i>0){
			return findTaskPage();
		}else{
			msg="删除失败！";
		return findTaskPage();
		}
		}
		/**
		 * 分页查询所有的 
		 * @return
		 */
		public String queryEndTask(){
			request = ServletActionContext.getRequest();
		    response = ServletActionContext.getResponse();
		    HttpSession session = request.getSession();
		    pageBean=taskService.queryEndTaskPage(3, page, search);	
			taskList=pageBean.getList();	
			request.setAttribute("taskList", taskList);
			request.setAttribute("pageBean", pageBean);	
			return "queryEndTask";
			
			
		}
		/**
		 * 批量删除结束的任务
		 * @return
		 */
		public String deleteAllTask2(){
			int i= taskService.deleteAllTask(number);
			if(i>0){
				return queryEndTask();
			}else{
				msg="删除失败！";
			return queryEndTask();
			}
		}
		/**
		 * 删除task
		 */
		public String deleteTask2(){
		int i= taskService.deleteTask(task.getTaskId());
		if(i>0){
			return queryEndTask();
		}else{
			msg="删除失败！";
		return queryEndTask();
		}
		}
	/**
	 * 微信发布需求页面
	 * @return
	 */
	public String releaseTaskPage(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
	    HttpSession session = request.getSession();	
		user=userService.queryuserById(user.getId());
		request.setAttribute("user",user);
		request.setAttribute("openId",user.getWeChatId());
		return "releaseTaskPage";
		
	}
	/**
	 * 发布需求	
	 * @return
	 */
	public String queryfaTask(){
		
		request = ServletActionContext.getRequest();
        response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();	
			   user=userService.queryUserInfo(user);
			 String taskTotalBonus = request.getParameter("taskTotalBonus");
			 double taskTotalBonu = Double.parseDouble(taskTotalBonus);
			int type = 0;
	        String[] str = { ".jpg", ".jpeg", ".bmp" ,".png",".gif"};  
	        //限定文件大小是4MB  
	        if(fileTest!=null){
	        if(fileTest.length()>2097152 ){  
	        	msg ="图片大小超出了2M";
	            return releaseTaskPage();  
	        } else{ 
	        
	        for (String s : str) {  
	            if (fileTestFileName.endsWith(s)) {  
	            	type =1;
	              String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
	               // String realPath ="d:/upload/faceimages";
	            	System.out.println(realPath);
	            	fileTestFileName=Tools.getRandomFileName()+s;
	                File saveFile = new File(new File(realPath),fileTestFileName);  //在该实际路径下实例化一个文件  
	                //判断父目录是否存在  
	                if(!saveFile.getParentFile().exists()){  
	                    saveFile.getParentFile().mkdirs();  
	                }  
	                try {  
	                    //执行文件上传  
	                    //FileUtils 类名 org.apache.commons.io.FileUtils;  
	                    //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
	                    FileUtils.copyFile(fileTest, saveFile);  
	                    task.setTaskLogo("faceimages/"+fileTestFileName);
	                      
	                } catch (IOException e) {  
	                	msg ="图片上传失败";
	                    return releaseTaskPage();  
	                }  
	            }  
	        }  
	        if(type== 0){
	        	msg = "上传的图片类型错误";
	        	return releaseTaskPage();
	        }
	        }
	        }
	        if(fileTest1!=null){
	            if(fileTest1.length()>2097152 ){  
	            	msg ="图片未上传或者图片大小超出了2M";
	                return releaseTaskPage();  
	            } else{ 
	                   
	            for (String s : str) {  
	                if (fileTest1FileName.endsWith(s)) {  
	                	type =1;
	                   String realPath = ServletActionContext.getServletContext().getRealPath("/faceimages");//实际路径 
	                    //String realPath ="d:/upload/faceimages";
	                	System.out.println(realPath);
	                	fileTest1FileName=Tools.getRandomFileName()+s;
	                    File saveFile = new File(new File(realPath),fileTest1FileName);  //在该实际路径下实例化一个文件  
	                    //判断父目录是否存在  
	                    if(!saveFile.getParentFile().exists()){  
	                        saveFile.getParentFile().mkdirs();  
	                    }  
	                    try {  
	                        //执行文件上传  
	                        //FileUtils 类名 org.apache.commons.io.FileUtils;  
	                        //是commons-io包中的，commons-fileupload 必须依赖 commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写  
	                        FileUtils.copyFile(fileTest1, saveFile);  
	                        task.setTaskOr("faceimages/"+fileTest1FileName);
	                          
	                    } catch (IOException e) {  
	                    	msg ="图片上传失败";
	                        return releaseTaskPage();  
	                    }  
	                }  
	            }  
	            if(type== 0){
	            	msg = "上传的图片类型错误";
	            	return releaseTaskPage();
	            }
	            }
	            }
	       
	        task.setUser(user);
	        task.setTaskStatus(0);
	        double nalance = (taskTotalBonu*0.006);
			NumberFormat formatter = new DecimalFormat("#0.00");
			    String nana = formatter.format(nalance);//（四舍五入）
			        double xiaoshu = Double.parseDouble(nana);
	        task.setHeji(taskTotalBonu+xiaoshu);
	        task.setShouxu(xiaoshu);
	        task.setTaskTotalBonus(taskTotalBonu);
	        Date date =new Date();
		   SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		   String  sd=sdf.format(date);
		   task.setPubTime(sd);
		   task.setTaskCode(taskService.getTaskCode());
		   if(taskTitle!=null&&!"".equals(taskTitle.trim())){
			   task.setTaskTitle(taskTitle);
		   }
		   if(taskTitle1!=null&&!"".equals(taskTitle1.trim())){
			   task.setTaskTitle(taskTitle1);
		   }
		   if(taskTitle2!=null&&!"".equals(taskTitle2.trim())){
			   task.setTaskTitle(taskTitle2);
		   }

		   int i=taskService.addTask(task);
		   if(i==1){
		   request.setAttribute("task", task); 
		   request.setAttribute("openId", user.getWeChatId());
		   }
           
		return "queryPayPage";
		
	}
	/**
	 * 需求列表
	 * @return
	 */
	public String queryTaskList(){
	request = ServletActionContext.getRequest();
    response = ServletActionContext.getResponse();	
     //分页查询需求
      Pager pagexq = taskService.queryTaskxq(10, page, user.getId());	
      List<Task> pagexqlist = pagexq.getList();
      int Total = pagexq.getTotalPage();
      System.err.println();
//    taskList=taskService.queryTaskList(user.getId());
//    request.setAttribute("taskList", taskList);
    request.setAttribute("pagexqlist", pagexqlist);
    request.setAttribute("Total", Total);
    request.setAttribute("page", page);
    user=userService.queryuserById(user.getId());
    request.setAttribute("user", user);
    request.setAttribute("openId",user.getWeChatId());
	return "queryTaskList";	
	}
	/**
	 * 支付页面
	 * @return
	 */
	public String payPage(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();	
	    user=userService.queryuserById(user.getId());
	    request.setAttribute("user", user);
		task=taskService.queryTaskById(task.getTaskId());
		task.setTaskStatus(4);
        int i=taskService.updateTask(task);
		 
		 request.setAttribute("task", task);
		 request.setAttribute("openId", user.getWeChatId());
		 return "queryPayPage";
	}
	/**
	 * 支付
	 */
	public String payTask(){
	   task=taskService.queryTaskById(task.getTaskId());
		 task.setTaskStatus(4);
		 int i=taskService.updateTask(task);
		 msg="支付未开通，需求已提交，请等待客服联系！";
		 user=userService.queryuserById(user.getId());
		
		return payPage(); 
	}
	
	/**
	 * 需求详情
	 * @return
	 */
	public String  queryTaskinfo(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();	
	   user=userService.queryuserById(user.getId());
	    request.setAttribute("user", user);
		task=taskService.queryTaskById(task.getTaskId());
		 request.setAttribute("task", task);
		 request.setAttribute("openId", user.getWeChatId());
		 return "queryTaskinfo"; 	
	}
	
	
	
	public String getSMSCheckCode(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 dataMap=new HashMap<String, Object>();
		 HashMap<String, Object> result = null; 
		 CCPRestSDK restAPI = new CCPRestSDK();
		 String mobile=request.getParameter("mobile");
		 String userId=request.getParameter("userId");
		 User user=userService.queryuserById(Long.parseLong(userId));
		 restAPI.init("app.cloopen.com","8883");
		 // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883. 
		 restAPI.setAccount("8a48b5514a61a814014a7faa434e11bb","4aeffdba4df3435aa816609728dd5052");
		 // 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在"控制台-应用"中看到开发者主账号ACCOUNT SID和 
		 // 主账号令牌AUTH TOKEN。
		 restAPI.setAppId("aaf98f894a70a61d014a7fe71da8099d");
		 // 初始化应用ID，如果是在沙盒环境开发，请配置"控制台-应用-测试DEMO"中的APPID。
		 //如切换到生产环境，请使用自己创建应用的APPID
		 String checkCode=getSix();
		 System.out.println(checkCode);
		 dataMap.put("code", checkCode);
		 result = restAPI.sendTemplateSMS(mobile,"103035",new String[]{user.getUsername(),checkCode});
		 System.out.println("SDKTestGetSubAccounts result=" + result); 
		 if("000000".equals(result.get("statusCode"))){
		 //正常返回输出data包体信息（map）
		 HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
		 Set<String> keySet = data.keySet();
		 for(String key:keySet){ 
		 Object object = data.get(key); 
		 System.out.println(key +" = "+object); 
		 dataMap.put("codeT", 1);
		 }
		 }else{
		 //异常返回输出错误码和错误信息
		 System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
		 dataMap.put("codeT", 0);
		 dataMap.put("msg", result.get("statusMsg"));
		 }
		 response.setHeader("Access-Control-Allow-Origin", "*");
		return "dataMap";
	}

	public String getTaskAll() throws ParseException{
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 String code=request.getParameter("code");
		if(code!=null){
			String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	        String requestUrl = o_auth_openid_url.replace("APPID","wx9d49f59517209fb7").replace("SECRET","8ce29d6424530ba7e803dc4c8146c794").replace("CODE",code);
	        JSONObject jsonObject=Utils.httpsRequest(requestUrl,"GET",null);
	        String openId=jsonObject.getString("openid");
	        request.setAttribute("openId", openId);	
	        User user=userService.queryMoneyOfUser(openId);
	        List<Task> list=taskService.getTaskAll(user,null,null);
	        int a=0;
			int b=0;
			for (int i = 0; i < list.size(); i++) {
				int taskRemainderNumber=list.get(i).getTaskTotalNumber()-list.get(i).getTaskNumber();
				 list.get(i).setTaskRemainderNumber(taskRemainderNumber);
				 
				 if (list.get(i).getTaskStatus()==1) {
					a+=1;
				}else if (list.get(i).getTaskStatus()==2){
					b+=1;
				}
				 
			}
				request.setAttribute("a",a);
				request.setAttribute("b",b);
			    request.setAttribute("list",list);
			    return "index";
		}
		else{
			String openId=request.getParameter("openId");
			String status=request.getParameter("taskStatus");
			String type=request.getParameter("taskType");
			Integer taskStatus=null;
			Integer taskType=null;
			User user=userService.queryMoneyOfUser(openId);
			if(status!=null&&!status.equals("")){
				 taskStatus=Integer.parseInt(status);
			}
			if(type!=null&&!type.equals("")){
				 taskType=Integer.parseInt(type);
			}
			
			List<Task> list=taskService.getTaskAll(user,taskStatus,taskType);
	        int a=0;
			int b=0;
			for (int i = 0; i < list.size(); i++) {
				int taskRemainderNumber=list.get(i).getTaskTotalNumber()-list.get(i).getTaskNumber();
				 list.get(i).setTaskRemainderNumber(taskRemainderNumber);
				 
				 if (list.get(i).getTaskStatus()==0) {
					a+=1;
				}else {
					b+=1;
				}
			}
				request.setAttribute("a",a);
				request.setAttribute("b",b);
			    request.setAttribute("list",list);
			    request.setAttribute("openId",openId);
			    request.setAttribute("taskStatus",taskStatus);
			    request.setAttribute("taskType",taskType);
			    return "index";
		}
	}
	
	public String orderDetails(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String openId=request.getParameter("openId");
		UserTask userTask=userTaskService.queryUserTaskById(Long.parseLong(request.getParameter("userTaskId")));
		request.setAttribute("task",userTask);
		request.setAttribute("openId",openId);
		if(userTask.getTaskStatus()==5||userTask.getTaskStatus()==1){
			return "orderdetails2";
		}else{
			return "orderdetails";
		}
		
	}
	
	public String GoOnCompleteTask() throws IOException{
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 
		String path = ServletActionContext.getServletContext().getRealPath("/uploads");
		/*long taskId=Long.parseLong(request.getParameter("taskId"));
		Task task=taskService.queryTaskById(taskId);*/
		File file = new File(path);
		// 如果指定的路径没有就创建
		if (!file.exists()) {
			file.mkdirs();
		}
		
		ActionContext context = ActionContext.getContext();
		Map params = context.getParameters();
		String username = (String) params.get("fileName");
        
		
		/*FileUtils.copyFile(upload[0], new File(file, "uploads/"+uploadFileName[0]+uploadContentType[0]));
		FileUtils.copyFile(upload[1], new File(file, "uploads/"+uploadFileName[1]+uploadContentType[1]));
		FileUtils.copyFile(upload[2], new File(file, "uploads/"+uploadFileName[2]+uploadContentType[2]));
		FileUtils.copyFile(upload[3], new File(file, "uploads/"+uploadFileName[3]+uploadContentType[3]));*/
		
		/*TaskImg taskImg=new TaskImg();
		String imgUrl="uploads/"+uploadFileName[0]+uploadContentType[0];
		String img1Url="uploads/"+uploadFileName[1]+uploadContentType[1];
		String img2Url="uploads/"+uploadFileName[2]+uploadContentType[1];
		String img3Url="uploads/"+uploadFileName[3]+uploadContentType[1];
		taskImg.setImgUrl(imgUrl);
		taskImg.setImg1Url(img1Url);
		taskImg.setImg2Url(img2Url);
		taskImg.setImg3Url(img3Url);
		taskImg.setTask(task);
		taskImgService.addTaskImg(taskImg);*/
		return null;
	}
	
	public String upload() throws IOException, FileUploadException{
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 String savePath =ServletActionContext.getServletContext().getRealPath("/uploads");
			File f1 = new File(savePath);
			System.out.println(savePath);
			if (!f1.exists()) {
				f1.mkdirs();
			}
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setHeaderEncoding("utf-8");
			List fileList = null;
			try {
				fileList = upload.parseRequest(request);
			} catch (FileUploadException ex) {
				return null;
			}
			Iterator<FileItem> it = fileList.iterator();
			String name = "";
			String extName = "";
			while (it.hasNext()) {
				FileItem item = it.next();
				if (!item.isFormField()) {
					name = item.getName();
					long size = item.getSize();
					String type = item.getContentType();
					System.out.println(size + " " + type);
					if (name == null || name.trim().equals("")) {
						continue;
					}
					//扩展名格式：  
					if (name.lastIndexOf(".") >= 0) {
						extName = name.substring(name.lastIndexOf("."));
					}
					File file = null;
					do {
						//生成文件名：
						name = UUID.randomUUID().toString();
						file = new File(savePath + name + extName);
					} while (file.exists());
					File saveFile = new File(savePath + name + extName);
					try {
						item.write(saveFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			response.getWriter().print(name + extName);

			return null;
	}
	
	
	
	
	public String getThoseTaskCompleted(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 long userId=Long.parseLong(request.getParameter("userId"));
		 List<Task> list=taskService.getThoseTaskscompleted(userId);
		 User user=userService.queryuserById(userId);
		 request.setAttribute("list",list);
		 request.setAttribute("openId",user.getWeChatId());
		return "missionCommission";
	}
	//进入任务
	public String  queryMoneyOfUser(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		HttpSession session1 = request.getSession();
//		String openIdl=request.getParameter("openId");
//		String openIdb=(String) request.getAttribute("openId");
//		System.out.println(openIdb);
//		User user=new User();
		    Object user1 = session1.getAttribute("user");
			
		if(user1!=null){
			 user=userService.queryuserById((Long)user1);
		}else{
			 user=userService.queryuserById((Long)user1);
		}
		
		request.setAttribute("user",user);
		request.setAttribute("openId",user.getWeChatId());
		return "wallet";
	}
	//提现查询
	public String queryBankcardOfUser(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 String userId1=request.getParameter("userId");
		long userId=Long.parseLong(userId1);
		User user=userService.queryuserById(userId);
		String mobile=request.getParameter("mobile");
		Bankcard bankcard=cardService.queryBankcardOfUser(userId);
		
		if(bankcard==null){
			request.setAttribute("userId",user.getId());
			request.setAttribute("openId",user.getWeChatId());
			return "bindingBankcard";
		}else{
			String cardCode=bankcard.getCardCode();
			String modil = bankcard.getCardMobile();
			String lastmodile = modil.substring(0,3)+"****"+modil.substring(7,modil.length());
				request.setAttribute("lastmodile", lastmodile);
				request.setAttribute("modil", modil);
		request.setAttribute("bankcard", bankcard);
		response.setHeader("Access-Control-Allow-Origin", "*");
		String lastFour=cardCode.substring(cardCode.length()-4,cardCode.length()); 
		request.setAttribute("lastFour", lastFour);
		request.setAttribute("openId",user.getWeChatId());
		return "moneyCashPostal";
		}
	}
	
	public String getSix() {
		Random rad = new Random();
		String result = rad.nextInt(1000000) + "";
		if (result.length() != 6) {
			return getSix();
		}
		return result;
	}
	
	
	/*
	public String taskRequirement(){
		request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		request.setAttribute("task",task);
		
		return "taskRequirement";
	}
	
	public String taskDetail(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		request.setAttribute("task",task);
		return "taskDetail";
	}*/
	
	public String weChatOfficialAccountsTaskDetails(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 HttpSession session = request.getSession();	
		 Long userid = (Long) session.getAttribute("user");
		    
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		ActionContext.getContext().getSession();
		if(openId!=null){
			 user=userService.queryMoneyOfUser(openId);
		}else {
			 user=userService.queryuserById(userid);
		}
		
		Task task=taskService.queryTaskById(Long.parseLong(taskId));

		 List<UserTask> userTask = userTaskService.queryUserTasks(Long.parseLong(taskId),user.getId());
		request.setAttribute("task",task);
		
		request.setAttribute("openId",openId);
		if(userTask!=null){
			for (UserTask userTask2 : userTask) {
				if(userTask2.getTaskStatus()==5 || userTask2.getTaskStatus()==2||userTask2.getTaskStatus()==1){
					request.setAttribute("taskStatus",userTask2.getTaskStatus());
					request.setAttribute("UserTaskId",userTask2.getUserTaskId());
				}
				request.setAttribute("randomCodeStained",userTask2.getRandomCode());
			}
			}
		
		if(task.getTaskType()==1){
//			Task task=taskService.queryTaskById(Long.parseLong(taskId));
			User user1=userService.queryMoneyOfUser(openId);
			UserTask userTask1=new UserTask();
			userTask1.setUser(user);
			userTask1.setTaskId(Long.parseLong(taskId));
			userTask1.setTaskTitle(task.getTaskTitle());
			if(user1.getUserLevel()==1){
				userTask1.setTaskBonus(task.getTaskBonus1());
			}
			if(user1.getUserLevel()!=1){
				userTask1.setTaskBonus(task.getTaskBonus());
			}
			userTask1.setTaskOrderCode(userTaskService.getOrderCode());
			userTask1.setTaskLogo(task.getTaskLogo());
			userTask1.setRandomCode(task.getRandomCode());
			userTask1.setTaskBriefing(task.getTaskBriefing());
			userTask1.setTaskStatus(6);
			userTask1.setOriginalID(task.getOriginalID());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date());
			userTask1.setTaskOrderTime(date);
			String randomCode=Tools.getRandomString();
			userTask1.setRandomCode(randomCode);
			userTask1.setTaskEndTime(task.getTaskEndTime());
			userTask1.setTaskType(task.getTaskType());
			 UserTask userTask2 = userTaskService.queryUaserTask(task.getTaskId(),user1.getId());
			if(userTask2!=null){
				request.setAttribute("randomCode",randomCode);
				userTaskService.addUserTask(userTask1);	
			}
			
			return "weChatOfficialAccountsTaskDetails";
		}else if(task.getTaskType()==2){
			List<TaskImg> list=taskImgService.queryTaskImg(task.getTaskId());
			
			request.setAttribute("list",list);
			
			return "advertisementFocusOnTask";
		}else{
			return "appDownloadDetails";
		}
	}
	
	public String weChatOfficialAccountsTaskDetails2(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		request.setAttribute("task", task);
		return "advertisementFocusOnTask2";
		
	}
	
	/*public String doWeixinTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user=userService.queryMoneyOfUser(openId);
		UserTask userTask=new UserTask();
		userTask.setUser(user);
		userTask.setTaskId(Long.parseLong(taskId));
		userTask.setTaskTitle(task.getTaskTitle());
		userTask.setTaskLogo(task.getTaskLogo());
		userTask.setTaskBriefing(task.getTaskBriefing());
		userTask.setTaskBonus(task.getTaskBonus());
		userTask.setTaskStatus(5);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		userTask.setTaskOrderTime(date);
		
		userTask.setTaskCompletionTime(task.getTaskEndTime());
		userTask.setTaskType(task.getTaskType());
		
		
		userTaskService.addUserTask(userTask);
		dataMap.put("msg",1);
		return "dataMap";
	}
	*/
	public String doAppDownloadTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user=userService.queryMoneyOfUser(openId);
		UserTask userTask=new UserTask();
		userTask.setUser(user);
		userTask.setTaskId(Long.parseLong(taskId));
		userTask.setTaskTitle(task.getTaskTitle());
		userTask.setTaskLogo(task.getTaskLogo());
		if(task.getTaskRemainderNumber()>0){
			task.setTaskRemainderNumber(task.getTaskRemainderNumber()-1);
			taskService.updateTask(task);
		
		if(user.getUserLevel()==1){
			userTask.setTaskBonus(task.getTaskBonus());
			     double a = task.getTaskBonus() / 0.3 * 0.05;
			     BigDecimal   b   =   new   BigDecimal(a);  
			     double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			     System.out.println("aaaaaaaaaaaaaaaaa:"+f1);
			userTask.setYongjing(f1);
			double a2 = task.getTaskBonus() / 0.3 * 0.1;
			   BigDecimal   b2   =   new   BigDecimal(a2);  
			     double   f2   =   b2.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			     System.out.println("aaaaaaaaaaaaaaaaa:"+f1);
			userTask.setTuiguang(f2);
		}
		if(user.getUserLevel()!=1){
//			userTask.setTaskBonus(task.getTaskBonus());
			   double yj = (task.getTaskTotalBonus() / task.getTaskTotalNumber())*0.4;
			   BigDecimal b2 = new BigDecimal(yj);  
			     double   f2   =   b2.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			userTask.setTaskBonus(f2);
			userTask.setTuiguang(0D);
			  double a = (task.getTaskTotalBonus() / task.getTaskTotalNumber()) * 0.05;
			     BigDecimal   b   =   new   BigDecimal(a);  
			     double   tg   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			userTask.setYongjing(tg);
		}
		userTask.setTaskOrderCode(userTaskService.getOrderCode());
		userTask.setTaskBriefing(task.getTaskBriefing());
		userTask.setTaskStatus(5);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		userTask.setTaskOrderTime(date);
		
		userTask.setTaskEndTime(task.getTaskEndTime());
		userTask.setTaskType(task.getTaskType());
		userTaskService.addUserTask(userTask);
		dataMap.put("msg",1);
		}
		return "dataMap";
	}
	
	public String appRegisterName(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		long userTaskId=Long.parseLong(request.getParameter("userTaskId"));
		String appRegisterName=request.getParameter("appRegisterName");
		userTaskService.updateUserTaskAppRegisterName(userTaskId, appRegisterName);
		UserTask task1 = userTaskService.queryUserTaskById(userTaskId);
		if(task1.getTaskStatus()!=null&&task1.getTaskStatus()==1){
			task1.setTaskStatus(5);
			task1.setTaskId(userTaskId);
		 int i = userTaskService.updateUserTask(task1);
		}
			dataMap.put("msg", 1);
		return "dataMap";
	}
	
	public String yemiantiaozhuan1(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user=userService.queryMoneyOfUser(openId);
		 UserTask userTask = userTaskService.queryUaserTask(Long.parseLong(taskId),user.getId());
//		int taskRemainderNumber=task.getTaskTotalNumber()-task.getTaskNumber();
//		request.setAttribute("taskRemainderNumber",taskRemainderNumber);
		if(userTask!=null){
		
				
				request.setAttribute("taskStatus",userTask.getTaskStatus());	
	
		}
		List<TaskImg> list=taskImgService.queryTaskImg(task.getTaskId());
		request.setAttribute("list",list);
		request.setAttribute("task",task);
		request.setAttribute("openId",openId);
		return "advertisementFocusOnTaskIntrduction";
	}
	
	public String yemiantiaozhuan2(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user=userService.queryMoneyOfUser(openId);
		 UserTask userTask = userTaskService.queryUaserTask(Long.parseLong(taskId),user.getId());
		/*int taskRemainderNumber=task.getTaskTotalNumber()-task.getTaskNumber();
		request.setAttribute("taskRemainderNumber",taskRemainderNumber);*/
		if(userTask!=null){
				
				request.setAttribute("taskStatus",userTask.getTaskStatus());	
		
		}
		List<TaskImg> list=taskImgService.queryTaskImg(task.getTaskId());
		request.setAttribute("list",list);
		request.setAttribute("task",task);
		request.setAttribute("openId",openId);
		return "advertisementFocusOnTask2";
	}
	
	public String myTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		     HttpSession session1 = request.getSession();
		     
		String taskId=request.getParameter("taskId");
//		String openId=request.getParameter("openId");
		    Long  user1 = (Long) session1.getAttribute("user");
		User user=userService.queryuserById(user1);
		long userId=user.getId();
		//分页查询
		Pager pagelist = userTaskService.queryMyTask(10, page, user1);
//		System.err.println("pagelist=---------"+pagelist);
		int Total = pagelist.getTotalPage();
		List<UserTask> pagetask = pagelist.getList();
//		System.err.println("pagetask=-------------"+pagetask);
//		List<UserTask> list=userTaskService.queryPeopleTask(userId);
//		request.setAttribute("list",list);
		request.setAttribute("pagetask",pagetask);
		request.setAttribute("page",page);
		request.setAttribute("Total",Total);
		request.setAttribute("openId",user.getWeChatId());
		return "myTask";
	}
	
	
	
	
	
	
	public String taskRequirement(){
		request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		request.setAttribute("task",task);
		
		return "taskRequirement";
	
	}
	public String taskDetail(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		request.setAttribute("task",task);
		
		return "taskDetail";
	}
	
	/*public String weChatOfficialAccountsTaskDetails(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
//		System.out.println(openId);
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		UserTask userTask=userTaskService.queryUaserTask(Long.parseLong(taskId));
		int taskRemainderNumber=task.getTaskTotalNumber()-task.getTaskNumber();
		request.setAttribute("task",task);
		request.setAttribute("taskRemainderNumber",taskRemainderNumber);
		request.setAttribute("openId",openId);
		if(userTask!=null){
			request.setAttribute("taskStatus",userTask.getTaskStatus());	
		}
		
		if(task.getTaskType()==1){
			return "weChatOfficialAccountsTaskDetails";
		}else if(task.getTaskType()==2){
			return "appDownloadDetails";
		}else{
			return "advertisementFocusOnTask";
		}
	}
	*/
	public String doWeixinTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user1=userService.queryMoneyOfUser(openId);
		UserTask userTask=new UserTask();
		userTask.setUser(user1);
		userTask.setTaskId(Long.parseLong(taskId));
		userTask.setTaskTitle(task.getTaskTitle());
		if(user1.getUserLevel()==1){
			userTask.setTaskBonus(task.getTaskBonus());	
		}
		if(user1.getUserLevel()!=1){
			userTask.setTaskBonus(task.getTaskBonus1());
		}
		userTask.setTaskOrderCode(userTaskService.getOrderCode());
		userTask.setTaskLogo(task.getTaskLogo());
		userTask.setRandomCode(task.getRandomCode());
		userTask.setTaskBriefing(task.getTaskBriefing());
		userTask.setTaskStatus(5);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		userTask.setTaskOrderTime(date);
		
		userTask.setTaskEndTime(task.getTaskEndTime());
		userTask.setTaskType(task.getTaskType());
		
		
		userTaskService.addUserTask(userTask);
		dataMap.put("msg",1);
		
		/*dataMap.put("user",user);*/
		return "dataMap";
	}
	
	/*public String doAppDownloadTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		User user=userService.queryMoneyOfUser(openId);
		UserTask userTask=new UserTask();
		userTask.setUser(user);
		//userTask.setTaskId(Long.parseLong(taskId));
		userTask.setTaskTitle(task.getTaskTitle());
		userTask.setTaskLogo(task.getTaskLogo());
		userTask.setTaskBriefing(task.getTaskBriefing());
		userTask.setTaskBonus(task.getTaskBonus());
		userTask.setTaskStatus(5);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		userTask.setTaskOrderTime(date);
		
		userTask.setTaskCompletionTime(task.getTaskEndTime());
		userTask.setTaskType(task.getTaskType());
		userTaskService.addUserTask(userTask);
		dataMap.put("msg",1);
		return "dataMap";
	}
	*/
	//添加到我的任务
	public String doAdvertisementTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		User user=userService.queryMoneyOfUser(openId);
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		UserTask userTask=new UserTask();
		if(task.getTaskRemainderNumber()>0){
		userTask.setUser(user);
		userTask.setTaskId(Long.parseLong(taskId));
		userTask.setTaskTitle(task.getTaskTitle());
		userTask.setTaskLogo(task.getTaskLogo());
		userTask.setTaskBriefing(task.getTaskBriefing());
		if(user.getUserLevel()==1){
			userTask.setTaskBonus(task.getTaskBonus());
			     double a = task.getTaskBonus() / 0.3 * 0.05;
			     BigDecimal   b   =   new   BigDecimal(a);  
			     double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			userTask.setYongjing(f1);
			double a2 = task.getTaskBonus() / 0.3 * 0.1;
			   BigDecimal   b2   =   new   BigDecimal(a2);  
			     double   f2   =   b2.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			     userTask.setTaskBonus1(task.getTaskBonus());
			     userTask.setTuiguang(f2);
		}else if(user.getUserLevel()!=1){
			System.err.println("我是会员");
//			userTask.setTaskBonus(task.getTaskBonus());
			   double yj = (task.getTaskTotalBonus() / task.getTaskTotalNumber())*0.4;
			   BigDecimal b2 = new BigDecimal(yj);  
			     double   f2   =   b2.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			     double sj = (task.getTaskTotalBonus() / task.getTaskTotalNumber())*0.3;
			     BigDecimal b3 = new BigDecimal(sj);  
			     double   f3   =   b3.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
			     userTask.setTaskBonus1(f3);
			userTask.setTaskBonus(f2);
			userTask.setTuiguang(0D);
			  double a = (task.getTaskTotalBonus() / task.getTaskTotalNumber()) * 0.05;
			     BigDecimal   b   =   new   BigDecimal(a);  
			     double   tg   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
			userTask.setYongjing(tg);

		}		
		userTask.setTaskOrderCode(userTaskService.getOrderCode());
		      
		if(task.getShengc()==1&&task.getShengc()!=null&&task.getShengc()!=2){
			
			userTask.setTaskStatus(1);
		}else {
			
			userTask.setTaskStatus(5);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		userTask.setTaskOrderTime(date);
		
		userTask.setTaskEndTime(task.getTaskEndTime());
		userTask.setTaskType(task.getTaskType());
		
		
		 UserTask userTask1 = userTaskService.queryUaserTask(Long.parseLong(taskId), user.getId());
		 
		 if(userTask1==null){
			 userTaskService.addUserTask(userTask);
			task.setTaskRemainderNumber(task.getTaskRemainderNumber()-1);
			int i=taskService.updateTask(task);
			request.setAttribute("task", task);	
				dataMap.put("msg",1);
			}else {
				dataMap.put("msg",2);
			}
			}else {
				dataMap.put("msg",3);
			}
		return "dataMap";
	}
	
	/*public String appRegisterName(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap=new HashMap<String, Object>();
		long userTaskId=Long.parseLong(request.getParameter("userTaskId"));
		String appRegisterName=request.getParameter("appRegisterName");
		//userTaskService.updateUserTaskAppRegisterName(userTaskId, appRegisterName);
		dataMap.put("msg", 1);
		
		return "dataMap";
	}*/
	
/*	public String yemiantiaozhuan1(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		UserTask userTask=userTaskService.queryUaserTask(Long.parseLong(taskId));
		int taskRemainderNumber=task.getTaskTotalNumber()-task.getTaskNumber();
		request.setAttribute("taskRemainderNumber",taskRemainderNumber);
		if(userTask!=null){
			request.setAttribute("taskStatus",userTask.getTaskStatus());	
		}
		request.setAttribute("task",task);
		return "advertisementFocusOnTaskIntrduction";
	}
	*/
	/*public String yemiantiaozhuan2(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		Task task=taskService.queryTaskById(Long.parseLong(taskId));
		UserTask userTask=userTaskService.queryUaserTask(Long.parseLong(taskId));
		int taskRemainderNumber=task.getTaskTotalNumber()-task.getTaskNumber();
		request.setAttribute("taskRemainderNumber",taskRemainderNumber);
		if(userTask!=null){
			request.setAttribute("taskStatus",userTask.getTaskStatus());	
		}
		request.setAttribute("task",task);
		return "advertisementFocusOnTask2";
	}*/
	/*
	public String myTask(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String taskId=request.getParameter("taskId");
		String openId=request.getParameter("openId");
		User user=userService.queryMoneyOfUser(openId);
		long userId=user.getId();
		List<UserTask> list=userTaskService.queryPeopleTask(userId);
		request.setAttribute("list",list);
		request.setAttribute("openId",openId);
		return "myTask";
	}*/
	
	
	
	

	public static OAuthInfo getOAuthOpenId(String appid, String secret, String code ) {
	        OAuthInfo oAuthInfo = null;
	        String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx9d49f59517209fb7&secret=8ce29d6424530ba7e803dc4c8146c794&code=001cmQ5C0xq5Z92S4G4C08gP5C0cmQ53&grant_type=authorization_code";
	        String requestUrl = o_auth_openid_url.replace("APPID","wx9d49f59517209fb7").replace("SECRET", "8ce29d6424530ba7e803dc4c8146c794").replace("CODE", "0110cVdQ0vP02f2WxeaQ0WB0eQ00cVdB");
	       
//	        JSONObject jsonObject = request(requestUrl, "GET", null);
	        
	        //oAuthInfo是作者自己把那几个属性参数写在一个类里面了。
	        // 如果请求成功
	       /* if (null != jsonObject) {
	            try {
	                oAuthInfo = new OAuthInfo();
	                oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
	                oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
	                oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
	                oAuthInfo.setOpenId(jsonObject.getString("openid"));
	                oAuthInfo.setScope(jsonObject.getString("scope"));
	            } catch (JSONException e) {
	                oAuthInfo = null;
	                // 获取token失败
	                log.error("网页授权获取openId失败 errcode:{} errmsg:{}", jsonObject
	                        .getInt("errcode"), jsonObject.getString("errmsg"));
	            }
	        }*/
	        return oAuthInfo;
	    }
	

	public String getSMSCheckCode1(){
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
		 dataMap=new HashMap<String, Object>();
		 HashMap<String, Object> result = null; 
		 CCPRestSDK restAPI = new CCPRestSDK();
		 String mobile=request.getParameter("mobile");
		 restAPI.init("app.cloopen.com","8883");
		 // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883. 
		 restAPI.setAccount("8a48b5514a61a814014a7faa434e11bb","4aeffdba4df3435aa816609728dd5052");
		 // 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在"控制台-应用"中看到开发者主账号ACCOUNT SID和 
		 // 主账号令牌AUTH TOKEN。
		 restAPI.setAppId("aaf98f894a70a61d014a7fe71da8099d");
		 // 初始化应用ID，如果是在沙盒环境开发，请配置"控制台-应用-测试DEMO"中的APPID。
		 //如切换到生产环境，请使用自己创建应用的APPID
		 String checkCode=getSix();
		 System.out.println(checkCode);
		 dataMap.put("code", checkCode);
		 result = restAPI.sendTemplateSMS(mobile,"103035",new String[]{"",checkCode});
		 System.out.println("SDKTestGetSubAccounts result=" + result); 
		 if("000000".equals(result.get("statusCode"))){
		 //正常返回输出data包体信息（map）
		 HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
		 Set<String> keySet = data.keySet();
		 for(String key:keySet){ 
		 Object object = data.get(key); 
		 System.out.println(key +" = "+object); 
		 }
		 }else{
		 //异常返回输出错误码和错误信息
		 System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
		 }
		 response.setHeader("Access-Control-Allow-Origin", "*");
		return "dataMap";
	}
	
	/**
	 * 任务列表
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String  queryOnTask() throws UnsupportedEncodingException{
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
	    HttpSession session = request.getSession();
	    Long user1 = (Long) session.getAttribute("user");
	   
	    int taskType=0;
		int bounts=0;
	   String area=null;
	    user=userService.queryuserById(user1);
	    String bounts1=request.getParameter("bounts");
		String type=request.getParameter("taskType");
		String area1=request.getParameter("area");
		
	    if(type!=null&&!"".equals(type)){
	    	taskType=Integer.parseInt(type);
	    	request.setAttribute("taskType", taskType);
	    }
	    if(area1!=null&&!"".equals(area1)){
	    	
	    	area=area1;
	    	request.setAttribute("area", area);
	    }
	    if(bounts1!=null&&!"".equals(bounts1)){
	    	bounts=Integer.parseInt(bounts1);
	    	request.setAttribute("bounts", bounts);
	    }
	    taskList=taskService.onTaskList(taskType, bounts, area, user);
	    //分页查询任务
	    Pager pagetaask = taskService.queryTaskStar(20, page, search, taskType, bounts, area, user);
	    List<Task> pagetask = pagetaask.getList();
	    int Total = pagetaask.getTotalPage();
	    
		request.setAttribute("user", user);
//		request.setAttribute("taskList", taskList);
		request.setAttribute("pagetask", pagetask);
		request.setAttribute("Total", Total);
		request.setAttribute("page", page);
		request.setAttribute("openId", user.getWeChatId());
		return "queryOnTask";
	}
	
	 /**
     * 查看关注人
     * @return
     */
	public String findGuabzhuUser(){
		request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
	    HttpSession session = request.getSession();	
	    String openId=request.getParameter("openId");
		user=userService.queryMoneyOfUser(openId);
		List list=userTaskService.queryGuanZhuUser(task.getTaskId());
		request.setAttribute("user", user);
		request.setAttribute("list", list);
		request.setAttribute("openId", openId);
		return "findGuabzhuUser";
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public Task getTask() {
		return task;
	}
	public void setTask(Task task) {
		this.task = task;
	}
	public TaskService getTaskService() {
		return taskService;
	}
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}
	 public UserService getUserService() {
			return userService;
		}

		public void setUserService(UserService userService) {
			this.userService = userService;
		}
	
	public List<TaskScreenshot> getShotList() {
		return shotList;
	}

	public void setShotList(List<TaskScreenshot> shotList) {
		this.shotList = shotList;
	}

	public CardService getCardService() {
		return cardService;
	}

	public void setCardService(CardService cardService) {
		this.cardService = cardService;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public List<File> getUploadFileData() {
		return uploadFileData;
	}

	public void setUploadFileData(List<File> uploadFileData) {
		this.uploadFileData = uploadFileData;
	}

	public List<String> getUploadFileDataFileName() {
		return uploadFileDataFileName;
	}

	public void setUploadFileDataFileName(List<String> uploadFileDataFileName) {
		this.uploadFileDataFileName = uploadFileDataFileName;
	}

	public List<String> getUploadFileDataContentType() {
		return uploadFileDataContentType;
	}

	public void setUploadFileDataContentType(List<String> uploadFileDataContentType) {
		this.uploadFileDataContentType = uploadFileDataContentType;
	}

	public UserTaskService getUserTaskService() {
		return userTaskService;
	}
	public int getPage() {
		return page;
	}

	public void setUserTaskService(UserTaskService userTaskService) {
		this.userTaskService = userTaskService;
	}


	public void setPage(int page) {
		this.page = page;
	}

	public List<Task> getTaskList() {
		return taskList;
	}

	public void setTaskList(List<Task> taskList) {
		this.taskList = taskList;
	}

	public Pager getPageBean() {
		return pageBean;
	}

	public void setPageBean(Pager pageBean) {
		this.pageBean = pageBean;
	}

	public String getSearch() {
		return search;
	}
	public void setSearch(String search) {
		this.search = search;
	}
	public File getFileTest() {
		return fileTest;
	}

	public void setFileTest(File fileTest) {
		this.fileTest = fileTest;
	}

	public String getFileTestFileName() {
		return fileTestFileName;
	}

	public void setFileTestFileName(String fileTestFileName) {
		this.fileTestFileName = fileTestFileName;
	}

	public File getFileTest1() {
		return fileTest1;
	}

	public void setFileTest1(File fileTest1) {
		this.fileTest1 = fileTest1;
	}

	public String getFileTest1FileName() {
		return fileTest1FileName;
	}

	public void setFileTest1FileName(String fileTest1FileName) {
		this.fileTest1FileName = fileTest1FileName;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public String getTaskTitle() {
		return taskTitle;
	}

	public void setTaskTitle(String taskTitle) {
		this.taskTitle = taskTitle;
	}

	public String getTaskTitle1() {
		return taskTitle1;
	}

	public void setTaskTitle1(String taskTitle1) {
		this.taskTitle1 = taskTitle1;
	}

	public String getTaskTitle2() {
		return taskTitle2;
	}

	public void setTaskTitle2(String taskTitle2) {
		this.taskTitle2 = taskTitle2;
	}

	public String getCode1() {
		return code1;
	}

	public void setCode1(String code1) {
		this.code1 = code1;
	}

	public TaskImgService getTaskImgService() {
		return taskImgService;
	}

	public void setTaskImgService(TaskImgService taskImgService) {
		this.taskImgService = taskImgService;
	}

	public String getOpenId() {
		return openId;
	}
	public static PromptMessage getPromptMessage() {
		return promptMessage;
	}
	public void setOpenId(String openId) {
		this.openId = openId;
	}


	public static void setPromptMessage(PromptMessage promptMessage) {
		TaskAction.promptMessage = promptMessage;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public String getImgFileContentType() {
		return imgFileContentType;
	}

	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}

	public String getImgList() {
		return imgList;
	}

	public void setImgList(String imgList) {
		this.imgList = imgList;
	}

	public List<TaskImg> getTaskImgList() {
		return taskImgList;
	}

	public void setTaskImgList(List<TaskImg> taskImgList) {
		this.taskImgList = taskImgList;
	}

	public String getDateNum() {
		return dateNum;
	}

	public void setDateNum(String dateNum) {
		this.dateNum = dateNum;
	}

	public Long getTaskId() {
		return taskId;
	}

	public void setTaskId(Long taskId) {
		this.taskId = taskId;
	}

	public String getTaskCode() {
		return taskCode;
	}

	public void setTaskCode(String taskCode) {
		this.taskCode = taskCode;
	}
	
}
